<script setup>
import {
    Edit,
    Delete, Plus
} from '@element-plus/icons-vue'
import { ref } from 'vue'
const schools = ref([])
//声明一个异步的函数
import { schoolListService, schoolAddService, schoolUpdateService, schoolDeleteService } from "@/api/admin/school.js";
import { useTokenStore } from '@/stores/token.js';

import { ElMessage } from "element-plus";
const schoolList = async () => {
    let result = await schoolListService();
    schools.value = result.data;
}
schoolList();

const tokenStore = useTokenStore();

//控制添加分类弹窗
const dialogVisible = ref(false)

//表单引用
const schoolFormRef = ref()

const schoolModel = ref({
    name: '',
    schoolBadge: '',
    status: 1
})
const rules = {
    name: [
        { required: true, message: '请输入学校名称', trigger: 'blur' },
    ],
    schoolBadge: [
        { required: true, message: '请上传学校校徽', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' },
    ]
}

const addSchool = async () => {
    // 先进行表单验证
    await schoolFormRef.value.validate();

    //调用接口
    let result = await schoolAddService(schoolModel.value);
    ElMessage.success(result.msg ? result.msg : '添加成功')

    //调用获取所有文章分类的函数
    await schoolList();
    dialogVisible.value = false;
}

//定义变量,控制标题的展示
const title = ref('')

//展示编辑弹窗
const showDialog = (row) => {
    dialogVisible.value = true;
    title.value = '编辑学校'
    //数据拷贝
    schoolModel.value.name = row.name;
    schoolModel.value.schoolBadge = row.schoolBadge;
    schoolModel.value.status = row.status;
    //扩展id属性,将来需要传递给后台,完成分类的修改
    schoolModel.value.id = row.id
}

//上传成功的回调函数
const uploadSuccess = (result)=>{
    schoolModel.value.schoolBadge = result.data;
}

//编辑分类
const updateSchool = async () => {
    // 先进行表单验证
    await schoolFormRef.value.validate();

    let result = await schoolUpdateService(schoolModel.value);

    ElMessage.success(result.msg ? result.msg : '修改成功')

    await schoolList();

    dialogVisible.value = false;
}

//清空模型的数据
const clearData = () => {
    schoolModel.value.name = '';
    schoolModel.value.schoolBadge = '';
    schoolModel.value.status = 1; // 默认启用
}

import {ElMessageBox} from 'element-plus'

const deleteSchool = (row) => {
    // 提示用户确认框
    ElMessageBox.confirm(
        '你确认要删除该分类信息吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 调用接口
                await schoolDeleteService(row.id);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                // 刷新列表
                await schoolList();
            } catch (error) {
                if (error.response && error.response.status === 400) {
                    const errorMessage = error.response.data.message || '删除失败';
                    ElMessage({
                        type: 'error',
                        message: errorMessage,
                    });
                } else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败:' + error.message,
                    });
                }
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消了删除',
            });
        });
};

const handleStatusChange = async (row) => {
    try {
        await schoolUpdateService({ id: row.id, status: row.status, name: row.name, schoolBadge: row.schoolBadge });
        ElMessage.success('状态更新成功');
    } catch (error) {
        ElMessage.error('状态更新失败');
        // 状态回滚
        row.status = row.status === 1 ? 0 : 1;
    }
    await schoolList();
};

</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>学校管理</span>
                <div class="extra">
                    <el-button type="primary" :icon="Plus" @click="dialogVisible = true; title = '添加学校'; clearData()">添加学校</el-button>
                </div>
            </div>
        </template>
        <el-table :data="schools" style="width: 100%">
            <el-table-column label="序号" width="100" type="index" align="center"></el-table-column>
            <el-table-column label="学校名称" prop="name" align="center"></el-table-column>
            <el-table-column label="学校校徽" align="center">
                <template #default="scope">
                    <el-image
                        style="width: 80px; height: 80px; border-radius: 5px"
                        :src="scope.row.schoolBadge"
                        :preview-src-list="[scope.row.schoolBadge]"
                        fit="cover"
                        preview-teleported
                    />
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" align="center">
                <template #default="{ row }">
                    <el-switch
                        v-model="row.status"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleStatusChange(row)"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220" align="center">
                <template #default="{ row }">
                    <el-button :icon="Edit" type="primary" @click="showDialog(row)">编辑</el-button>
                    <el-button :icon="Delete" type="danger" @click="deleteSchool(row)">删除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据"/>
            </template>
        </el-table>

        <!-- 添加/编辑学校弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="35%">
            <el-form :model="schoolModel" :rules="rules" label-width="100px" style="padding-right: 30px" ref="schoolFormRef">
                <el-form-item label="学校名称" prop="name">
                    <el-input v-model="schoolModel.name" minlength="1" maxlength="20" placeholder="请输入学校名称"></el-input>
                </el-form-item>
                <el-form-item label="学校校徽" prop="schoolBadge">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                               action="/api/upload"
                               name="file"
                               :headers="{'Authorization':tokenStore.token}"
                               :on-success="uploadSuccess"
                    >
                        <img v-if="schoolModel.schoolBadge" :src="schoolModel.schoolBadge" class="avatar"
                             style="width: 120px;height: 120px;border-radius: 10px;" alt="学校校徽"/>
                        <el-icon v-else class="avatar-uploader-icon" style="width: 120px;height: 120px;border-radius: 10px;border: 1px dashed #d9d9d9;">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="schoolModel.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="title === '添加学校' ? addSchool() : updateSchool()">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>
